<template>
  <md-nav-bar
    title=""
    color="white"
    :bgInfo="{
      url: data.detail.coverUrl || 'https://cdn.xmxiaomai.com/isong_static/evaluation/indexTopBg.png',
      height: '685rpx'
    }" />
  <!-- 分享按钮 -->
<!--  <image-->
<!--    src="https://cdn.xmxiaomai.com/isong_static/music/%E5%88%86%E4%BA%AB.png"-->
<!--    class="shareIcon"-->
<!--    @click="handleShare" />-->
  <!-- 歌曲信息卡片 -->
  <view class="music-info-card">
    <!-- 唱片播放区 -->
    <view class="record-background">
      <view class="disc-bg">
        <view class="record-wrap" @click="onPlay">
          <view class="record">
            <image
              class="record-img"
              :src="data.detail?.coverUrl || 'https://cdn.xmxiaomai.com/isong_static/evaluation/indexTopBg.png'"
              mode="aspectFill" />
            <image class="record-center" src="https://cdn.xmxiaomai.com/isong_static/evaluation/play.png" />
          </view>
        </view>
      </view>
    </view>
    <!-- 歌曲信息卡片 -->
    <view class="music-title">{{ data.detail.name }}</view>
    <view class="music-meta">
      <view>作词：{{ data.detail.wording }}</view>
      <view>作曲：{{ data.detail.composer }}</view>
    </view>
    <view class="music-meta">
      <view>演唱：{{ data.detail.singer }}</view>
      <view>时间：{{ data.detail.createTime }}</view>
    </view>
    <view class="music-btns">
      <view class="music-btn" @click="onBg">创作背景</view>
      <view class="music-btn" @click="onLyric">查看歌词</view>
      <view class="music-btn" @click="handleShare">我要分享</view>
    </view>
    <view class="music-stats">
      <!-- 点赞数 -->
      <view class="stat-item">
        <image src="https://cdn.xmxiaomai.com/isong_static/music/%E8%B5%9E%403x.png" />
        {{ data.detail.likesNum }}
      </view>
      <!-- 留言数 -->
      <view class="stat-item">
        <image src="https://cdn.xmxiaomai.com/isong_static/music/ping.png" />
        {{ data.detail.commentNum }}
      </view>
      <!-- 分享数 -->
      <view class="stat-item">
        <image src="https://cdn.xmxiaomai.com/isong_static/music/%E8%BD%AC%403x.png" />
        {{ data.detail.collectNum }}
      </view>
    </view>
  </view>
  <view class="music-ai-eval-container" v-if="data.detail.evaluationRecords?.evaluationStatus == 0">
    <!-- AI评价卡片 -->
    <view class="ai-eval-card">
      <view class="ai-score-bg">
        <view class="ai-score-badge">
          <view class="ai-score-num">{{ data.detail.evaluationRecords?.aiScore || 0 }}</view>
        </view>
      </view>
      <view class="ai-score-title">AI综合评分</view>
      <view class="ai-hr"></view>
      <view class="ai-section" >
        <mp-html
            :content="data.detail.evaluationRecords?.songEvaluation"
            container-style="display:flex;font-size: 30rpx; text-align: justify;"
            :tag-style="{
              p: 'padding:20rpx',
              ul: 'padding:20rpx 0 20rpx 40rpx'
            }"
        ></mp-html>
      </view>
      <view class="ai-section-tip">测评结果为AI大模型算法自动生成，仅供参考</view>
    </view>
  </view>
  <view class="music-ai-eval-container" v-else>
    <view class="music-ai-eval-fail" v-if="data.detail.evaluationRecords?.evaluationStatus == 1">测评中，请稍等</view>
    <view class="music-ai-eval-fail" v-if="data.detail.evaluationRecords?.evaluationStatus == 2" style="color: red">
      测评失败，请重试
    </view>
  </view>
  <!-- 底部按钮 -->
  <view class="btns-wrap">
    <view v-for="item in data.btns" :key="item.value" class="btn" :class="[item.class]" @click="() => handleBtn(item.value)">
      {{ item.label }}
    </view>
  </view>
  <!-- 分享弹窗 -->
  <uni-popup ref="share" type="share" safeArea backgroundColor="#fff">
    <uni-popup-share title="分享" @select="selectShare"></uni-popup-share>
  </uni-popup>
  <!-- 发布和设置 -->
  <uni-popup ref="modal" type="bottom" safeArea backgroundColor="#fff">
    <view class="modal-style">
      <uni-title type="h1" title="设置" />
      <uni-forms ref="form" :modelValue="data.formData" :rules="data.rules" label-position="left" label-width="100">
        <!-- 封面 -->
        <uni-forms-item label="封面" name="coverUrl" required>
          <uni-file-picker
            v-model="data.formData.coverUrl"
            return-type="object"
            file-mediatype="image"
            :image-styles="{ height: '160rpx', width: '100%' }"
            @select="(e: any) => handleUpload(e, 'coverUrl')">
            <view class="upload-box">
              <text class="plus">+</text>
            </view>
          </uni-file-picker>
        </uni-forms-item>
        <!-- 是否发布到广场 -->
        <uni-forms-item label="发布到音乐广场" name="isShowMusic">
          <uni-data-checkbox v-model="data.formData.isShowMusic" :localdata="data.options" />
        </uni-forms-item>
        <!-- 公开测评分数 -->
        <uni-forms-item label="公开测评结果" name="isShowEvaluation">
          <uni-data-checkbox v-model="data.formData.isShowEvaluation" :localdata="data.options" />
        </uni-forms-item>
        <!-- 公开测评分数 -->
        <uni-forms-item label="公开测评分数" name="isShowScore">
          <uni-data-checkbox v-model="data.formData.isShowScore" :localdata="data.options" />
        </uni-forms-item>
        <uni-forms-item label="作词" name="wording">
          <uni-easyinput type="text" v-model="data.formData.wording" placeholder="请输入作词" />
        </uni-forms-item>
        <uni-forms-item label="作曲" name="composer">
          <uni-easyinput type="text" v-model="data.formData.composer" placeholder="请输入作曲" />
        </uni-forms-item>
        <uni-forms-item label="演唱" name="singer">
          <uni-easyinput type="text" v-model="data.formData.singer" placeholder="请输入演唱" />
        </uni-forms-item>
        <uni-forms-item label="创作背景" name="background">
          <uni-easyinput
            type="textarea"
            :maxlength="2000"
            v-model="data.formData.background"
            placeholder="请输入创作背景" />
        </uni-forms-item>
      </uni-forms>
      <view class="modal-btn">
        <view class="btn" @click="handleCancel">取消</view>
        <view class="btn" @click="handleSubmit">提交</view>
      </view>
    </view>
  </uni-popup>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app';

// 接口
import api from '@/api';
import type { Music } from '@/api/data';
import { downloadFileFromResponse, uploadToQiniu } from '@/api/util';

const data = reactive({
  id: null,
  userId: '',
  detail: {} as Music.Detail.Data,
  evaluationInfo: {} as Omit<Music.GetMusicEvaluation.Data, 'lyricsEvaluation' | 'songEvaluation'> & {
    lyricsEvaluation: Record<string, any>;
    songEvaluation: Record<string, any>;
  },
  btns: [
    { label: '删除', value: 'delete', class:'delete-btn' },
    { label: '公开', value: 'setting', class: 'setting-btn' },
  ],
  formData: {} as Record<string, any>,
  rules: {
    coverUrl: {
      rules: [
        {
          required: true,
          errorMessage: '请上传封面',
        },
      ],
    },
  },
  options: [
    {
      text: '是',
      value: 1,
    },
    {
      text: '否',
      value: 0,
    },
  ],
});

// const evalTabs = ['歌词评价', '旋律评价', '总结'];
// const evalTab = ref(0);
const share = ref<any>(null);
const modal = ref<any>(null);
const form = ref(null);

// 分享
const handleShare = () => {
  share.value?.open?.();
};

// 选择分享的模块
const selectShare = (e: any) => {
  const { item } = e;
  // 海报
  if (item.name == 'hb') {
    // 处理逻辑
    console.log('分享海报');
    fetchGetPoster();
  }
};

function onBg() {
  uni.setStorageSync('background', data.detail?.background);
  uni.navigateTo({
    url: `/pages/sub/index/musicBackground`,
  });
}
function onLyric() {
  uni.navigateTo({
    url: `/pages/sub/square/musicPlayer?id=${data.detail?.id}&type=my`,
  });
}

// 跳转播放页面
function onPlay() {
  uni.navigateTo({
    url: `/pages/sub/square/musicPlayer?id=${data.detail.id}&type=my`,
  });
}

/**
 * 设置和发布弹窗的表单处理
 */

const handleBtn = (key: string) => {
  if (key === 'delete') {
    uni.showModal({
      title: '提示',
      content: '是否确认删除该音乐？',
      success: res => {
        if (res.confirm) {
          fetchDeleteMusic();
        }
      },
    });
  }
  if (key === 'setting') {
    modal.value?.open();
  }
};

const handleCancel = () => {
  modal.value?.close();
};

const handleSubmit = async () => {
  try {
    const res = await form.value?.validate();
    // 处理提交格式
    const values = {
      coverUrl: res?.coverUrl?.url,
      isShowMusic: res?.isShowMusic,
      isShowScore: res?.isShowScore,
      isShowEvaluation: res?.isShowEvaluation,
      background: res?.background,
      wording: res?.wording,
      composer: res?.composer,
      singer: res?.singer,
    };
    await fetchUpdateMusic(values);
  } catch (error) {}
};

/**
 * 封面上传处理
 */
const handleUpload = async (e: any, key: string) => {
  uni.showLoading({ title: '上传中...', mask: true });
  let { tempFiles } = e;
  const file = tempFiles?.[0];
  try {
    const res: any = await uploadToQiniu(file, 'isong/music/' + key);
    if (res) {
      // 格式化组件需要的格式
      const value = {
        url: res.url,
        extname: res?.extname,
        name: res?.name,
      };
      data.formData[key] = value;
    } else {
      data.formData[key] = {};
    }
  } catch (e) {
    data.formData[key] = {};
  }
  uni.hideLoading();
};

/**
 * 接口相关
 */
// 音乐详情
const fetchGetDetail = async (id: number) => {
  try {
    const res = await api.Music.myDetail({ id });
    data.detail = res.data;
    // data.detail.evaluationRecords.songEvaluation = marked(res.data?.evaluationRecords?.songEvaluation);
    const _extname = res.data?.coverUrl?.split('.')?.slice(-1)?.[0];
    data.formData = {
      coverUrl: res.data?.coverUrl ? { url: res.data?.coverUrl, extname: _extname, name: res.data?.name } : undefined,
      isShowMusic: res.data?.isShowMusic ? 1 : 0,
      isShowScore: res.data?.isShowScore ? 1 : 0,
      isShowEvaluation: res.data?.isShowEvaluation ? 1 : 0,
      wording: res.data?.wording,
      composer: res.data?.composer,
      singer: res.data?.singer,
      background: res.data?.background,
    };
  } catch (error) {}
};

// 音乐测评记录
const fetchGetMusicEvaluation = async (id: number) => {
  try {
    const res = await api.Music.getMusicEvaluation({
      musicId: id,
    });
    data.evaluationInfo = {
      ...res.data,
      lyricsEvaluation: res.data.lyricsEvaluation ? JSON.parse(res.data.lyricsEvaluation) : '',
      songEvaluation: res.data.songEvaluation ? JSON.parse(res.data.songEvaluation) : '',
    };
  } catch (error) {}
};

// 更新音乐配置
const fetchUpdateMusic = async (params: Record<string, any>) => {
  try {
    await api.Music.update({
      ...data.detail,
      id: Number(data.id),
      ...params,
    });
    uni.showModal({
      title: '提示',
      content: '修改成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          handleCancel();
          fetchGetDetail(Number(data.id));
        }
      },
    });
  } catch (error) {}
};

// 删除音乐
const fetchDeleteMusic = async () => {
  try {
    await api.Music.delete({ id: Number(data.id) });
    uni.navigateBack();
  } catch (error) {}
};

// 分享海报
const fetchGetPoster = async () => {
  try {
    await uni.showLoading({
      title: '生成中...',
    });
    const res = await api.Music.getPoster({ id: Number(data.id) });
    console.log('海报',res)
    if (res.code === 0 && res.data){
      try {
        wx.downloadFile({
          url: res.data,
          success: function (res) {
            if (res.statusCode === 200) {
              console.log('下载成功，临时路径：', res.tempFilePath);
              wx.previewImage({
                urls: [res.tempFilePath],
                current: res.tempFilePath,
              });
              uni.hideLoading();
            } else {
              wx.showToast({
                title: '下载失败',
                icon: 'none'
              });
              uni.hideLoading();
            }
          },
          fail: function (err) {
            console.error('下载失败：', err);
            wx.showToast({
              title: '下载失败',
              icon: 'none'
            });
            uni.hideLoading();
          }
        });
      }catch (e) {
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        });
        uni.hideLoading();
      }
    }else{
      wx.showToast({
        title: '下载失败',
        icon: 'none'
      });
      uni.hideLoading();
    }

  } catch (error) {}
};

onLoad((options: any) => {
  data.id = options.id;
  data.userId = uni.getStorageSync('auth')?.userId;
  fetchGetDetail(options.id);
  // fetchGetMusicEvaluation(options.id);
});

// 分享
onShareAppMessage(async _ => {
  if (!data.detail.isShowMusic) {
    uni.showModal({
      title: '请先发布音乐',
      icon: 'none',
    })
    return
  }
  return {
    title: data.detail?.name || 'isong music',
    imageUrl: data.detail?.coverUrl || 'https://cdn.xmxiaomai.com/isong_static/share.jpg',
    path: "/pages/sub/square/musicDetail?id=" + data.detail.id + (data.userId ? ('&parentId=' + data.userId) : ''),
  };
});
</script>

<style lang="scss" scoped>
.music-ai-eval-container {
  background: white;
  padding-top: 160rpx;
  margin-top: 20rpx;
  padding-bottom: calc(45rpx + $safe-bottom + 108rpx);
}
.music-ai-eval-fail {
  background: #eee;
  width: 600rpx;
  height: 200rpx;
  text-align: center;
  line-height: 200rpx;
  margin-left: 75rpx;
  border-radius: 30rpx;
}
.header-bg {
  position: relative;
  width: 100vw;
  height: 320rpx;
  overflow: hidden;
}
.bg-img {
  width: 100vw;
  height: 320rpx;
  object-fit: cover;
  display: block;
}
.header-bar {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 2;
  padding: 0 24rpx;
}
.shareIcon {
  width: 50rpx;
  height: 50rpx;
  position: absolute;
  right: 40rpx;
  top: 254rpx;
}
.back {
  font-size: 44rpx;
}
.header-actions {
  display: flex;
  align-items: center;
}
.share {
  font-size: 36rpx;
  margin-left: 24rpx;
}
.record-background {
  width: 100%;
  height: 180rpx;
  position: relative;
  .disc-bg {
    width: 390rpx;
    height: 276rpx;
    position: relative;
    border-radius: 20rpx;
    overflow: hidden;
    background-image: url('https://cdn.xmxiaomai.com/isong_static/evaluation/discBg.png');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    top: -160rpx;
    bottom: 0;
    left: 55rpx;
    right: 0;
    margin: auto;
  }
}
.record-wrap {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 3;
}
.record {
  width: 279rpx;
  height: 276rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border-radius: 20rpx;
  overflow: hidden;
}
.record-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.record-center {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 90rpx;
  height: 90rpx;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}
.music-info-card {
  background: #fff;
  border-radius: 48rpx 48rpx 0 0;
  margin-top: -200rpx;
  padding: 32rpx 32rpx 24rpx 32rpx;
  box-shadow: 0 4rpx 24rpx 0 #e0e0e0;
  position: relative;
  z-index: 2;
}
.music-title {
  font-size: 36rpx;
  color: #222;
  font-weight: 700;
  margin-bottom: 30rpx;
}
.music-meta {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #444;
  margin-bottom: 4rpx;
}
.music-meta > view {
  margin-right: 32rpx;
}
.music-btns {
  display: flex;
  align-items: center;
  margin-top: 18rpx;
}
.music-btn {
  background: #fff;
  color: #1fa37a;
  border: 2rpx solid #1fa37a;
  border-radius: 32rpx;
  font-size: 28rpx;
  padding: 0 32rpx;
  height: 56rpx;
  line-height: 56rpx;
  margin-right: 18rpx;
  font-weight: 500;
}
.music-stats {
  display: flex;
  align-items: center;
  margin-top: 18rpx;
}
.stat-item {
  display: flex;
  align-items: center;
  font-size: 34rpx;
  color: #1fa37a;
  margin-right: 32rpx;
  gap: 4rpx;
  & > image {
    width: 34rpx;
    height: 34rpx;
  }
}
.ai-eval-card {
  width: 660rpx;
  background: #fff8ed;
  border-radius: 32rpx;
  margin: 0 auto;
  padding: 32rpx 24rpx 24rpx 24rpx;
  box-shadow: 0 4rpx 24rpx 0 #ffe7b2;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.ai-score-bg {
  width: 318.43rpx;
  height: 163.95rpx;
  background: url('https://cdn.xmxiaomai.com/isong_static/music/Group%2015%403x.png') no-repeat center center;
  background-size: cover;
  margin-top: -120rpx;
  margin-bottom: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.ai-score-badge {
  width: 120rpx;
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.ai-score-num {
  font-size: 38rpx;
  color: #b88a2a;
  font-weight: 700;
}
.ai-score-title {
  font-size: 30rpx;
  color: #1fa37a;
  font-weight: 600;
  margin-bottom: 8rpx;
}
.ai-score-desc {
  font-size: 26rpx;
  color: #444;
  margin-bottom: 18rpx;
  text-align: center;
}
.ai-hr {
  width: 100%;
  height: 1rpx;
  border: 2rpx solid #85c5b6;
  margin: 24rpx 0;
}
.ai-eval-tabs {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
  background: white;
  width: 100%;
  height: 68rpx;
  border-radius: 32rpx;
  padding: 7rpx 21rpx;
  box-sizing: border-box;
  gap: 18rpx;
}
.eval-tab {
  flex: 1;
  font-size: 28rpx;
  color: #1fa37a;
  padding: 8rpx 32rpx;
  box-sizing: border-box;
  text-align: center;
}
.eval-tab.active {
  background: #1fa37a;
  color: #fff;
  border-radius: 24rpx;
}
:deep(.ai-section .mp-html) {
  width: 100%;
  h3 {
    font-size: 28rpx;
    margin-bottom: 10rpx;
    color: #1fa37a;
  }
  p {
    display: flex;
    align-items: flex-start;
    font-size: 26rpx;
    color: #444;
  }
}
.ai-section-title {
  font-size: 28rpx;
  color: #1fa37a;
  font-weight: 600;
  margin: 18rpx 0 8rpx 0;
  align-self: flex-start;
  .ai-icon {
    width: 30rpx;
    height: 30rpx;
    vertical-align: middle;
    margin-right: 12rpx;
  }
}
.ai-section-list {
  width: 100%;
  margin-bottom: 8rpx;
}
.ai-section-item {
  font-size: 26rpx;
  color: #444;
  margin-bottom: 6rpx;
  display: flex;
  align-items: flex-start;
  white-space: pre-wrap;
}
.ai-section-num {
  color: #1fa37a;
  margin-right: 6rpx;
}
.ai-section-summary {
  font-size: 26rpx;
  color: #444;
  margin-bottom: 8rpx;
  text-align: left;
  width: 100%;
}
.ai-section-tip {
  font-size: 22rpx;
  color: #bbb;
  margin-top: 18rpx;
  align-self: flex-start;
}
.btns-wrap {
  position: fixed;
  bottom: 0;
  left: 0;
  background: black;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 22rpx;
  padding-bottom: $safe-bottom;
  box-sizing: border-box;
  border-top: 1rpx solid #ddd;
  gap: 50rpx;
  .btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    border: none;
    border-radius: 50rpx;
    //padding: 20rpx 30rpx;
    width: 24%;
    color: #fff;
    height: 70rpx;
    line-height: 70rpx;
    font-size: 28rpx;

    &::after {
      border: none;
    }
  }

  .setting-btn {
    background-color: rgba(0, 122, 255, 0.7);
  }

  .delete-btn {
    background-color: rgba(255, 59, 48, 0.7);
  }
}
.modal-style {
  width: 100%;
  height: 1350rpx;
  padding: 24rpx;
  box-sizing: border-box;
  .modal-btn {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20rpx;
    padding: 0 40rpx;

    & > .btn {
      height: 80rpx;
      width: 40%;
      line-height: 80rpx;
      text-align: center;
      border-radius: 10rpx;
      border: 1rpx solid #ddd;
      padding: 0 16rpx;
      box-sizing: border-box;
      &:last-of-type {
        background: #01604a;
        color: white;
        border: 0;
      }
    }
  }
}

::v-deep .uni-forms-item{
  margin-bottom: 24rpx !important;
}

</style>
